<template>
  <title-container
    v-if="question"
    :id="question.outId"
    :index="index"
    :total="total"
    :error="error"
    :question.sync="question"
  >
    <div v-for="(item, index) in question.questionContent" :key="index" class="item">
      <a-checkbox :checked="item.checked" @change="onChange(item, index)">
        {{ item.content }}
      </a-checkbox>
      <a-textarea
        v-if="item.isBlank && item.checked"
        v-model="item.value"
        class="item_input"
        placeholder="填写内容..."
        :auto-size="{ minRows: 3, maxRows: 5 }"
        @blur="onBlur(item, index)"
      />
    </div>
  </title-container>
</template>

<script>
import TitleContainer from '@/components/titleContainer'
export default {
  name: 'Checkbox',
  components: {
    TitleContainer
  },
  props: {
    total: {
      type: Number,
      default: 0
    },
    index: {
      type: Number,
      default: 0
    },
    question: {
      type: Object,
      default: null
    },
    error: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      excludeMap: {}, // 是否存在互斥选项
    }
  },
  created() {
    this.question.questionTag = this.question.questionTag || []
    this.question.requiredFlag = this.question.requiredFlag === undefined ? true : this.question.requiredFlag
    this.question.questionContent.forEach((item, index) => {
      item.checked = !!item.checked
      // 是否存在互斥选项
      if (item.isExclude) {
        this.excludeMap[index] = item
      }
    })

    /**
       * 1.只设置了最少需选时显示：最少选择X1项
       * 2.只设置了最多可选时显示：最多选择X2项
       * 3.同时设置了最多可选、最少需选时显示：请选择X1-X2项。
       * 4.未设置最多可选、最少需选时不显示填写说明。
       */
    const minCount = this.question.questionMin || 0
    const maxCount = this.question.questionMax || 0
    let tag = '多选题'
    const message = this.getMessage()
    if (message) {
      tag = `${tag}，${message}`
    }
    this.question.questionTag.unshift(tag)
    // console.log('created', this.excludeMap, tag)
  },
  methods: {
    onChange(item, index) {
      // 超过多选限制时，不处理
      const result = this.getResult()
      const maxCount = this.question.questionMax || 0
      if (maxCount > 0 && result.length >= maxCount && !item.checked) {
        const message = this.getMessage()
        this.$emit('show-message', message)
        return false
      }
      item.checked = !item.checked
      this.forceUpdate(item, index)

      // 处理选项互斥的交互
      this.excludeList(item, index)
      this.submit()
    },

    // 1.若当前选中非互斥选项，将其他互斥选项设置为“未选中”状态
    // 2.若当前选中互斥选项，将其他非互斥选项设置为”未选中“状态
    excludeList(item, index) {
      // 不存在互斥选项时，不执行下面的互斥处理逻辑
      if (Object.keys(this.excludeMap).length === 0) return true

      if (!item.isExclude) {
        Object.keys(this.excludeMap).forEach(i => {
          const child = this.question.questionContent[i]
          child.checked = false
          this.forceUpdate(child, i)
        })
        return true
      }
      this.question.questionContent.forEach((child, i) => {
        if (index !== i && item.checked) {
          child.checked = false
          this.forceUpdate(child, i)
        }
      })
    },

    getMessage() {
      const minCount = this.question.questionMin || 0
      const maxCount = this.question.questionMax || 0
      let tag = ''
      if (minCount > 0 && maxCount > 0) {
        tag = `请选择${minCount}-${maxCount}项`
      } else if (minCount > 0) {
        tag = `最少选择${minCount}项`
      } else if (maxCount > 0) {
        tag = `最多选择${maxCount}项`
      }
      return tag
    },

    getResult() {
      // 拼接选中的选项
      const result = []
      this.question.questionContent.forEach((item, idx) => {
        if (!item.checked) return false
        if (item.require && !item.value) return false
        result.push({ index: idx, content: item.content, value: item.value })
      })
      return result
    },

    onBlur(item, index) {
      // console.log('blur', item, index)
      this.submit()
    },
    submit() {
      // console.log('submit')
      const index = this.index
      // 拼接选中的选项
      const result = this.getResult()

      // 要求为必填时，必须选择一项
      if (this.question.requiredFlag && result.length === 0) {
        return false
      }
      const minCount = this.question.questionMin || 0
      if (minCount > 0 && result.length < minCount) {
        return false
      }
      const maxCount = this.question.questionMax || 0
      if (maxCount > 0 && result.length > maxCount) {
        return false
      }
      const answer = {
        surveyId: this.question.surveyId,
        outId: this.question.outId,
        questionType: this.question.questionType,
        result: result
      }
      // console.log('暴露给父组件', answer, index)
      this.$emit('complete', answer, index)
    },
    forceUpdate(item, index) {
      this.$set(this.question.questionContent, index, item)
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.item{
  margin-bottom: 14px;
}
.item_input {
  margin-top: 14px;
}
</style>
